"""角色模板库"""

from typing import Dict, List, Any
from enum import Enum
from pydantic import BaseModel, Field
from .character import CharacterType

class CharacterClass(Enum):
    """角色职业"""
    WARRIOR = "warrior"        # 战士
    MAGE = "mage"             # 法师
    ARCHER = "archer"         # 弓箭手
    ASSASSIN = "assassin"     # 刺客
    HEALER = "healer"         # 治疗师
    TANK = "tank"             # 坦克
    BERSERKER = "berserker"   # 狂战士
    PALADIN = "paladin"       # 圣骑士
    NECROMANCER = "necromancer" # 死灵法师
    DRUID = "druid"           # 德鲁伊

class CharacterTemplate(BaseModel):
    """角色模板"""
    template_id: str = Field(..., description="模板ID")
    name: str = Field(..., description="角色名称")
    character_class: CharacterClass = Field(..., description="角色职业")
    description: str = Field("", description="角色描述")
    
    # 基础属性
    base_hp: int = Field(..., description="基础生命值")
    base_attack: int = Field(..., description="基础攻击力")
    base_defense: int = Field(..., description="基础防御力")
    base_speed: int = Field(..., description="基础速度")
    
    # 战斗属性
    base_hit_rate: int = Field(85, description="基础命中率")
    base_dodge_rate: int = Field(10, description="基础闪避率")
    base_crit_rate: int = Field(15, description="基础暴击率")
    base_crit_damage: int = Field(150, description="基础暴击伤害")
    
    # 成长属性（每级增长）
    hp_growth: int = Field(10, description="生命值成长")
    attack_growth: int = Field(2, description="攻击力成长")
    defense_growth: int = Field(1, description="防御力成长")
    speed_growth: int = Field(1, description="速度成长")
    
    # 默认技能
    default_skills: List[str] = Field(default_factory=list, description="默认技能ID列表")
    
    # 角色标签
    tags: List[str] = Field(default_factory=list, description="角色标签")
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        return {
            "template_id": self.template_id,
            "name": self.name,
            "character_class": self.character_class.value,
            "description": self.description,
            "base_attributes": {
                "hp": self.base_hp,
                "attack": self.base_attack,
                "defense": self.base_defense,
                "speed": self.base_speed,
                "hit_rate": self.base_hit_rate,
                "dodge_rate": self.base_dodge_rate,
                "crit_rate": self.base_crit_rate,
                "crit_damage": self.base_crit_damage
            },
            "growth_attributes": {
                "hp_growth": self.hp_growth,
                "attack_growth": self.attack_growth,
                "defense_growth": self.defense_growth,
                "speed_growth": self.speed_growth
            },
            "default_skills": self.default_skills,
            "tags": self.tags
        }
    
    def calculate_attributes_at_level(self, level: int) -> Dict[str, int]:
        """计算指定等级的属性"""
        level_bonus = max(0, level - 1)  # 1级为基础，从2级开始有成长
        
        return {
            "hp": self.base_hp + (self.hp_growth * level_bonus),
            "attack": self.base_attack + (self.attack_growth * level_bonus),
            "defense": self.base_defense + (self.defense_growth * level_bonus),
            "speed": self.base_speed + (self.speed_growth * level_bonus),
            "hit_rate": self.base_hit_rate,
            "dodge_rate": self.base_dodge_rate,
            "crit_rate": self.base_crit_rate,
            "crit_damage": self.base_crit_damage
        }

class CharacterTemplateLibrary:
    """角色模板库"""
    
    _templates: Dict[str, CharacterTemplate] = {}
    
    @classmethod
    def initialize_default_templates(cls):
        """初始化默认模板"""
        default_templates = [
            # 战士系
            CharacterTemplate(
                template_id="warrior_basic",
                name="基础战士",
                character_class=CharacterClass.WARRIOR,
                description="平衡的近战战士，攻防兼备",
                base_hp=120, base_attack=25, base_defense=18, base_speed=12,
                base_hit_rate=85, base_dodge_rate=8, base_crit_rate=12, base_crit_damage=140,
                hp_growth=12, attack_growth=3, defense_growth=2, speed_growth=1,
                default_skills=["basic_attack", "power_strike", "shield_bash", "steel_skin", "battle_frenzy", "regeneration"],
                tags=["近战", "平衡", "坚韧"]
            ),
            CharacterTemplate(
                template_id="tank_heavy",
                name="重装坦克",
                character_class=CharacterClass.TANK,
                description="超高防御的肉盾角色",
                base_hp=180, base_attack=15, base_defense=30, base_speed=8,
                base_hit_rate=75, base_dodge_rate=5, base_crit_rate=8, base_crit_damage=120,
                hp_growth=18, attack_growth=1, defense_growth=3, speed_growth=0,
                default_skills=["basic_attack", "shield_bash", "taunt", "steel_skin", "magic_shield", "thorn_counter"],
                tags=["坦克", "防御", "控制"]
            ),
            CharacterTemplate(
                template_id="berserker_fury",
                name="狂暴战士",
                character_class=CharacterClass.BERSERKER,
                description="高攻击高暴击的狂战士",
                base_hp=100, base_attack=35, base_defense=12, base_speed=16,
                base_hit_rate=88, base_dodge_rate=12, base_crit_rate=25, base_crit_damage=180,
                hp_growth=8, attack_growth=4, defense_growth=1, speed_growth=1,
                default_skills=["basic_attack", "power_strike", "whirlwind", "battle_frenzy", "berserker_soul", "agile_reflex"],
                tags=["输出", "暴击", "狂暴"]
            ),
            
            # 法师系
            CharacterTemplate(
                template_id="mage_elemental",
                name="元素法师",
                character_class=CharacterClass.MAGE,
                description="掌控元素力量的魔法师",
                base_hp=70, base_attack=40, base_defense=8, base_speed=18,
                base_hit_rate=92, base_dodge_rate=15, base_crit_rate=22, base_crit_damage=190,
                hp_growth=6, attack_growth=4, defense_growth=1, speed_growth=2,
                default_skills=["basic_attack", "fireball", "ice_shard", "eagle_eye", "lucky_strike", "magic_shield"],
                tags=["魔法", "远程", "爆发"]
            ),
            CharacterTemplate(
                template_id="necromancer_dark",
                name="黑暗死灵法师",
                character_class=CharacterClass.NECROMANCER,
                description="操控死亡力量的黑魔法师",
                base_hp=80, base_attack=35, base_defense=10, base_speed=15,
                base_hit_rate=90, base_dodge_rate=12, base_crit_rate=20, base_crit_damage=170,
                hp_growth=7, attack_growth=3, defense_growth=1, speed_growth=1,
                default_skills=["basic_attack", "life_drain", "curse", "regeneration", "thorn_counter", "berserker_soul"],
                tags=["魔法", "吸血", "召唤"]
            ),
            
            # 敏捷系
            CharacterTemplate(
                template_id="assassin_shadow",
                name="暗影刺客",
                character_class=CharacterClass.ASSASSIN,
                description="高速高暴击的刺客",
                base_hp=75, base_attack=32, base_defense=8, base_speed=25,
                base_hit_rate=95, base_dodge_rate=28, base_crit_rate=35, base_crit_damage=220,
                hp_growth=5, attack_growth=3, defense_growth=1, speed_growth=2,
                default_skills=["basic_attack", "backstab", "poison_blade", "agile_reflex", "eagle_eye", "lucky_strike"],
                tags=["敏捷", "暴击", "隐身"]
            ),
            CharacterTemplate(
                template_id="archer_ranger",
                name="游侠弓箭手",
                character_class=CharacterClass.ARCHER,
                description="精准的远程射手",
                base_hp=85, base_attack=30, base_defense=12, base_speed=20,
                base_hit_rate=98, base_dodge_rate=18, base_crit_rate=28, base_crit_damage=200,
                hp_growth=6, attack_growth=3, defense_growth=1, speed_growth=2,
                default_skills=["basic_attack", "multi_shot", "piercing_arrow", "eagle_eye", "agile_reflex", "swift_speed"],
                tags=["远程", "精准", "多目标"]
            ),
            
            # 辅助系
            CharacterTemplate(
                template_id="healer_priest",
                name="神圣牧师",
                character_class=CharacterClass.HEALER,
                description="专精治疗的神职人员",
                base_hp=90, base_attack=18, base_defense=15, base_speed=16,
                base_hit_rate=85, base_dodge_rate=20, base_crit_rate=8, base_crit_damage=130,
                hp_growth=8, attack_growth=2, defense_growth=2, speed_growth=1,
                default_skills=["basic_attack", "heal", "group_heal", "vitality", "magic_shield", "regeneration"],
                tags=["治疗", "辅助", "神圣"]
            ),
            CharacterTemplate(
                template_id="paladin_holy",
                name="圣骑士",
                character_class=CharacterClass.PALADIN,
                description="攻防兼备的圣战士",
                base_hp=130, base_attack=22, base_defense=20, base_speed=14,
                base_hit_rate=88, base_dodge_rate=12, base_crit_rate=15, base_crit_damage=150,
                hp_growth=10, attack_growth=2, defense_growth=2, speed_growth=1,
                default_skills=["basic_attack", "heal", "divine_strike", "steel_skin", "vitality", "magic_shield"],
                tags=["平衡", "神圣", "治疗"]
            ),
            CharacterTemplate(
                template_id="druid_nature",
                name="自然德鲁伊",
                character_class=CharacterClass.DRUID,
                description="与自然和谐的魔法师",
                base_hp=95, base_attack=25, base_defense=14, base_speed=17,
                base_hit_rate=87, base_dodge_rate=16, base_crit_rate=18, base_crit_damage=160,
                hp_growth=8, attack_growth=3, defense_growth=2, speed_growth=1,
                default_skills=["basic_attack", "heal", "nature_blessing", "regeneration", "thorn_counter", "vitality"],
                tags=["自然", "治疗", "多样"]
            )
        ]
        
        for template in default_templates:
            cls._templates[template.template_id] = template
    
    @classmethod
    def get_template(cls, template_id: str) -> CharacterTemplate:
        """获取角色模板"""
        if not cls._templates:
            cls.initialize_default_templates()
        
        if template_id not in cls._templates:
            raise ValueError(f"角色模板 '{template_id}' 不存在")
        
        return cls._templates[template_id]
    
    @classmethod
    def get_all_templates(cls) -> Dict[str, CharacterTemplate]:
        """获取所有角色模板"""
        if not cls._templates:
            cls.initialize_default_templates()
        
        return cls._templates.copy()
    
    @classmethod
    def get_templates_by_class(cls, character_class: CharacterClass) -> List[CharacterTemplate]:
        """根据职业获取模板"""
        if not cls._templates:
            cls.initialize_default_templates()
        
        return [template for template in cls._templates.values() 
                if template.character_class == character_class]
    
    @classmethod
    def get_templates_by_tag(cls, tag: str) -> List[CharacterTemplate]:
        """根据标签获取模板"""
        if not cls._templates:
            cls.initialize_default_templates()
        
        return [template for template in cls._templates.values() 
                if tag in template.tags]
    
    @classmethod
    def add_template(cls, template: CharacterTemplate):
        """添加新模板"""
        cls._templates[template.template_id] = template
    
    @classmethod
    def remove_template(cls, template_id: str):
        """移除模板"""
        if template_id in cls._templates:
            del cls._templates[template_id]
    
    @classmethod
    def create_character_from_template(cls, template_id: str, character_id: str, 
                                     character_type: CharacterType, level: int = 1):
        """从模板创建角色"""
        from .character import Character
        
        template = cls.get_template(template_id)
        attributes = template.calculate_attributes_at_level(level)
        
        return Character(
            id=character_id,
            name=template.name,
            character_type=character_type,
            max_hp=attributes["hp"],
            current_hp=attributes["hp"],
            attack=attributes["attack"],
            defense=attributes["defense"],
            speed=attributes["speed"],
            hit_rate=attributes["hit_rate"],
            dodge_rate=attributes["dodge_rate"],
            crit_rate=attributes["crit_rate"],
            crit_damage=attributes["crit_damage"],
            skills=template.default_skills.copy()
        )

# 初始化默认模板
CharacterTemplateLibrary.initialize_default_templates()